<script setup>
import {
  getCategoryListApi,
  delCategoryByIdApi,
  getCategoryByIdApi,
  addCategoryApi,
  updateCategoryApi
} from '@/apis/category'
import { uploadFileApi } from '@/apis/common'
import { Plus } from '@element-plus/icons-vue'
import { ref, defineEmits } from 'vue'
const tableData = ref([])
const emit = defineEmits(['title'])
emit('title', '分类管理')
const getCategoryList = async () => {
  const res = await getCategoryListApi()
  tableData.value = res.data.data
}

getCategoryList()

const dialogVisible = ref(false)
const formRef = ref(null)
const formDefault = {
  id: null,
  categoryName: '',
  categoryRank: null,
  ancestors: []
}
const formData = ref({
  id: null,
  carouselRank: null,
  categoryName: '',
  icon: '',
  ancestors: []
})
const formRules = {
  categoryName: [{ required: true, message: '请输入分类名', trigger: 'blur' }],
  categoryRank: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
}

const open = async (row) => {
  imgUrl.value = ''
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  if (row) {
    const res = await getCategoryByIdApi(row.id)
    formData.value = res.data.data
    imgUrl.value = res.data.data.icon
    formData.value.ancestors.splice(0, 1)
    console.log(formData.value)
  } else {
    formData.value = { ...formDefault }
  }

  dialogVisible.value = true
}

const onDelete = async (row) => {
  let flag = false
  await ElMessageBox.confirm('温馨提示', '确定删除吗？', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })

  if (row.children && row.children.length > 0) {
    await ElMessageBox.confirm('温馨提示', '存在子分类是否强制删除？', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    flag = true
  }

  // 删除
  await delCategoryByIdApi(row.id, flag)

  ElMessage({
    message: '删除成功',
    type: 'success'
  })

  getCategoryList()
}

const onSubmit = async () => {
  await formRef.value.validate()
  if (formData.value.id) {
    // 修改
    console.log('修改')
    await updateCategoryApi(formData.value)
  } else {
    // 新增
    console.log('新增')
    formData.value.icon = imgUrl.value
    await addCategoryApi(formData.value)
  }

  ElMessage({
    message: formData.value.id ? '修改成功' : '新增成功',
    type: 'success'
  })

  getCategoryList()
  dialogVisible.value = false
}

const handleChange = (e) => {
  console.log(e)
}

// 定义映射
const optionProps = {
  value: 'id',
  label: 'categoryName',
  children: 'children',
  checkStrictly: true
}

// 上传文件自定义图标
const imgUrl = ref('')

const onUpload = async (uploadFile) => {
  imgUrl.value = ''
  // console.log(uploadFile) // uploadFile.raw 就可以获取到上传的文件对象了
  // URL.createObjectURL(文件对象)  可以返回一个可供本地预览的文件地址
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  // 将文件对象赋值给 formModel 作为请求数据
  const fileData = new FormData()
  fileData.append('file', uploadFile.raw)
  // console.log(formData)
  const res = await uploadFileApi(fileData)
  formData.value.icon = res.data.data
}
</script>

<template>
  <div>
    <el-card style="max-width: 100%">
      <!-- 页头 -->
      <template #header>
        <div class="card-header">
          <el-button
            color="#52abad"
            style="color: #fff"
            :icon="Plus"
            @click="open(null)"
            >新增</el-button
          >
        </div>
      </template>

      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        height="550"
        row-key="id"
      >
        <el-table-column prop="categoryName" label="分类名" />
        <el-table-column prop="categoryRank" label="排序值" sortable />
        <el-table-column prop="icon" label="图标">
          <template #default="scope">
            <el-image
              :src="scope.row.icon"
              alt=""
              style="width: 1.3rem; height: 1.3rem"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" sortable />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="open(scope.row)"
            >
              修改
            </el-button>

            <el-button
              link
              type="danger"
              size="small"
              @click="onDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 弹层 -->
    <div>
      <el-dialog
        v-model="dialogVisible"
        :title="formData.id ? '修改分类' : '新增分类'"
        width="500"
      >
        <div class="form-box">
          <el-form
            ref="formRef"
            style="max-width: 22rem"
            :model="formData"
            :rules="formRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item
              label="上级分类"
              prop="parentId"
              v-show="formData.ancestors.length > 0 || formData.id == null"
            >
              <el-cascader
                v-model="formData.ancestors"
                :options="tableData"
                :props="optionProps"
                @change="handleChange"
              />
            </el-form-item>

            <el-form-item label="分类名" prop="categoryName">
              <el-input v-model="formData.categoryName" />
            </el-form-item>

            <el-form-item label="排序值" prop="categoryRank">
              <el-input
                v-model="formData.categoryRank"
                type="number"
                :min="0"
              />
            </el-form-item>

            <!-- 图片 -->
            <el-form-item label="图片" prop="icon" style="width: 10rem">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="onUpload"
              >
                <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmit">
              {{ formData.id ? '修改' : '新增' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
/* 文件上传样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 6.25rem;
      height: 6.25rem;
      display: block;
    }

    img {
      width: 6.25rem;
      height: 6.25rem;
      display: block;
    }

    .el-upload--picture-card,
    .el-upload-list__item {
      width: 6.25rem;
      height: 6.25rem;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 6.25rem;
      height: 6.25rem;
      text-align: center;
    }
  }
}
</style>
